package shark.picture.utils.hashToStr;

import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;

/**
 * 将字符串转换为hex，解决调用内网接口时的乱码问题
 *
 * @author user
 *
 */
public class StringHexUTF8Util {

	private static String HEXSTRING = "0123456789ABCDEF";

	public static String stringToHex(String str) throws UnsupportedEncodingException {
		// 根据默认编码获取字节数组
		byte[] bytes = str.getBytes("UTF-8");
		StringBuilder sb = new StringBuilder(bytes.length * 2);
		// 将字节数组中每个字节拆解成2位16进制整数
		for (int i = 0; i < bytes.length; i++) {
			sb.append(HEXSTRING.charAt((bytes[i] & 0xf0) >> 4));
			sb.append(HEXSTRING.charAt((bytes[i] & 0x0f) >> 0));
		}
		return sb.toString();
	}

	public static String hexToString(String bytes) throws UnsupportedEncodingException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream(bytes.length() / 2);
		// 将每2位16进制整数组装成一个字节
		for (int i = 0; i < bytes.length(); i += 2)
			baos.write((HEXSTRING.indexOf(bytes.charAt(i)) << 4 | HEXSTRING.indexOf(bytes.charAt(i + 1))));
		return new String(baos.toByteArray(), "UTF-8");
	}
	public static void main(String[] args) throws UnsupportedEncodingException {
		String toHex = StringHexUTF8Util.stringToHex("中午");
		System.out.println(toHex);
		System.out.println(hexToString(toHex));
		System.out.println(stringToHex("<DBSET><R><C N=\"business_no\">6,033</C><C N=\"cons_no\">0062697159</C><C N=\"meter_no\">1179266695</C><C N=\"contact_name\">戴路平</C><C N=\"contact_tel\">17770956510</C><C N=\"post_addr\">南丹东路218</C><C N=\"accept_time\">2017-11-20 18:01:01</C><C N=\"app_reason\">计量不准</C><C N=\"detect_mode\">02</C></R></DBSET>"));
	}
}
